package tum0r.server.problem.web.file_upload;

import tum0r.utils.extension.StringExtension;
import tum0r.utils.misc.GetClass;
import tum0r.utils.shell.Shell;
import tum0r.utils.shell.ShellResult;
import tum0r.webengine.model.server.EngineFile;
import tum0r.webengine.model.server.ErrorMessage;
import tum0r.webengine.utils.misc.Log;
import tum0r.webengine.utils.server.action.Action;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;

/**
 * 工程: Security<br>
 * 包: tum0r.server.problem.web.file_upload.direct<br>
 * 创建者: tum0r<br>
 * 创建时间: 2021/6/25 20:04<br>
 * <br>
 */
public class Exploit {
    public void upload(int problemID, EngineFile file, Action<String> action) throws ErrorMessage {
        String filePath = "upload" + File.separator + problemID + File.separator + file.getFileName();
        boolean result = file.saveFile(filePath);
        Shell shell = new Shell();
        ShellResult shellResult = shell.exec("javac " + filePath);
        action.check(!shellResult.isSuccess(), shellResult.getResult());
        action.callBack(result ? "保存成功，文件名: " + file.getFileName() : "保存失败");
    }

    public void exp(int problemID, String className, String payload, Action<String> action) throws ErrorMessage {
        action.check(StringExtension.isNullOrEmpty(className), "未找到此类");
        action.check(StringExtension.isNullOrEmpty(payload), "Payload不能为空");
        GetClass getClass = new GetClass();
        try {
            File file = new File("upload" + File.separator + problemID);
            Class<?> exploitClass = getClass.getClass(file.getAbsolutePath(), className);
            if (exploitClass != null) {
                Object object = exploitClass.getDeclaredConstructor().newInstance();
                Method exploitMethod = exploitClass.getMethod("exploit", String.class);
                payload = String.valueOf(exploitMethod.invoke(object, payload));
                Shell shell = new Shell();
                action.callBack(shell.exec(payload).getResult());
            } else {
                action.callBack("未能加载到文件");
            }
        } catch (MalformedURLException | ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            Log.error(e);
            action.check(true, "未找到此类");
        }
    }
}
